/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.cms.web.front;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.security.shiro.session.SessionDAO;
import com.thinkgem.jeesite.common.servlet.ValidateCodeServlet;
import com.thinkgem.jeesite.common.utils.BigNumberFormat;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.SendMessage;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.*;
import com.thinkgem.jeesite.modules.cms.service.*;
import com.thinkgem.jeesite.modules.cms.utils.CmsUtils;
import com.thinkgem.jeesite.modules.hk.shop.entity.shop.*;
import com.thinkgem.jeesite.modules.hk.shop.service.shop.*;
import com.thinkgem.jeesite.modules.hk.sys.entity.currency.HkShopCooperation;
import com.thinkgem.jeesite.modules.hk.sys.entity.user.HkUser;
import com.thinkgem.jeesite.modules.hk.sys.service.currency.HkShopCooperationService;
import com.thinkgem.jeesite.modules.hk.sys.service.user.HkUserService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.thinkgem.jeesite.modules.sys.security.UsernamePasswordToken;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网站Controller
 *
 * @author ThinkGem
 * @version 2013-5-29
 */
@Controller
@RequestMapping(value = "${frontPath}")
public class FrontController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(FrontController.class);


    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleDataService articleDataService;
    @Autowired
    private LinkService linkService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SiteService siteService;
    @Autowired
    private HkUserService hkUserService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private SessionDAO sessionDAO;
    @Autowired
    private HkEnterShopInfoService hkEnterShopInfoService;
    @Autowired
    private HkEnterShopCompanyInfoService hkEnterShopCompanyInfoService;
    @Autowired
    private HkShopTrademarkService hkShopTrademarkService;
    @Autowired
    private HkUserShopService hkUserShopService;
    @Autowired
    private HkShopReviewService hkShopReviewService;
    @Autowired
    private HkShopCooperationService hkShopCooperationService;
    @Autowired
    private AreaService areaService;

    private String tel = "";

    /**
     * 网站首页
     */
    @RequestMapping
    public String index(Model model) {
        Site site = CmsUtils.getSite(Site.defaultSiteId());
        model.addAttribute("site", site);
        model.addAttribute("isIndex", true);
        return "modules/cms/front/themes/" + site.getTheme() + "/frontIndex";
    }

    /**
     * 商家入驻页面
     */
    @RequestMapping(value = "enter")
    public String enter(Model model) {
        Site site = CmsUtils.getSite(Site.defaultSiteId());
        model.addAttribute("site", site);
        return "modules/cms/shop/enter";
    }

    /**
     * 下载页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "down")
    public String down(Model model) {
        Site site = CmsUtils.getSite(Site.defaultSiteId());
        model.addAttribute("site", site);
        return "modules/cms/shop/downApp";
    }

    /**
     * 企业合作
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "company")
    public String company(Model model) {
        Site site = CmsUtils.getSite(Site.defaultSiteId());
        model.addAttribute("site", site);
        return "modules/cms/shop/business";
    }

    private String getCode(HttpServletRequest request) {
        String code = BigNumberFormat.getAppCode();
        request.getSession().setAttribute("code", code);
        return code;
    }


    @RequestMapping(value = "open")
    public String open(Model model) {
        return "modules/cms/shop/agreement";
    }


    /**
     * 验证码
     */
    @RequestMapping(value = "yzm")
    @ResponseBody
    public Map yzm(String validateCode, String phone, HttpServletRequest request) {
        tel = phone;
        Map map = new HashMap();
        map.put("status", 0);
        if (StringUtils.isNotBlank(validateCode) && ValidateCodeServlet.validate(request, validateCode)) {
            String code = getCode(request);
            System.out.println(code);
            try {
                SendMessage.sendRegisterMessageCode(phone, code);
            } catch (Exception e) {
                map.put("status", 1);
                e.printStackTrace();
            }
            map.put("code", Integer.parseInt(code));
        }
        return map;
    }

    /**
     * 入驻
     */
    @RequestMapping(value = "register")
    public String register(String code, String phone, String validateCode, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
//        HkUserShop userShophr = hkUserShopService.getShopByUserName(phone);
        User user = systemService.findUserByLoginName(phone, "0");
        if (user != null) {
            addMessage(redirectAttributes, "手机号已注册，请直接登录！");
            request.setAttribute("isRegister", "该手机号已注册，请直接登录！");
            return "modules/cms/shop/enter";
        } else if (StringUtils.isBlank(phone)) {
            addMessage(redirectAttributes, "手机号不能为空！");
            request.setAttribute("isRegister", "手机号不能为空！");
            return "redirect:" + frontPath + "/enter";
        } else {
            HkUserShopEnter hkUserShopEnter = new HkUserShopEnter();
            String oldCode = request.getSession().getAttribute("code").toString();
            if (StringUtils.isNotBlank(code) && oldCode.equals(code)) {
                HkUser hkUser = new HkUser();
                hkUser.setMobile(phone);
                try {
                    hkUserService.register(hkUser);
                    autoLogin(phone, request, code, validateCode);
                    hkUserShopEnter.setManagerMobile(phone);
                    model.addAttribute("hkUserShopEnter", hkUserShopEnter);
                    return "modules/cms/shop/userShopEnter";
                } catch (Exception e) {
                    e.printStackTrace();
                    addMessage(redirectAttributes, "注册失败，请重新注册！");
                    return "modules/cms/shop/enter";
                }
            } else {
                addMessage(redirectAttributes, "验证码错误，请重新输入验证码！");
                return "modules/cms/shop/enter";
            }
        }
    }


    private void autoLogin(String phone, HttpServletRequest request, String code, String validateCode) {
        //org.apache.shiro.authc.UsernamePasswordToken token = new org.apache.shiro.authc.UsernamePasswordToken(phone, phone.substring(phone.length() - 6, phone.length()));
        UsernamePasswordToken token = new UsernamePasswordToken(phone, (phone.substring(phone.length() - 6, phone.length())).toCharArray(), false, StringUtils.getRemoteAddr((HttpServletRequest) request), validateCode, false);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            if (!currentUser.isAuthenticated()) {
                currentUser.login(token);//验证角色和权限
            }
        } catch (Exception e) {

        }

        User user = UserUtils.getByLoginName(phone);
        HkUserShop hkUserShop = hkUserShopService.getShopByUserId(user.getId());
        if (null != hkUserShop) {
            UserUtils.setShopId(hkUserShop.getId());
            request.getSession().setAttribute("loginName", phone);
        }

        log.info("autoLogin-shopId", UserUtils.getShopId());
        log.info("autoLogin-loginName", UserUtils.getSession().getAttribute("loginName"));

    }


    /**
     * 调试页面用
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "testPath")
    public String path(Model model) {
        /*HkEnterShopInfo hkEnterShopInfo = new HkEnterShopInfo();
        model.addAttribute("hkEnterShopInfo", hkEnterShopInfo);
        HkEnterShopCompanyInfo hkEnterShopCompanyInfo = new HkEnterShopCompanyInfo();
        model.addAttribute("hkEnterShopCompanyInfo", hkEnterShopCompanyInfo);
        HkShopTrademark hkShopTrademark = new HkShopTrademark();
        model.addAttribute(hkShopTrademark);
        HkUserShop hkUserShop = new HkUserShop();
        model.addAttribute("hkUserShop", hkUserShop);*/

        HkUserShopEnter hkUserShopEnter = new HkUserShopEnter();
        model.addAttribute("hkUserShopEnter", hkUserShopEnter);
        return "modules/cms/shop/userShopEnter";
    }


    /**
     * 登陆
     */
    @RequestMapping(value = "login")
    public String login(String username, String password, String validateCode, HttpServletRequest request, RedirectAttributes redirectAttributes, Model model) {

        User user = systemService.findUserByLoginName(username, "0");
//        if (UserUtils.getByLoginName(username) != null) {
        if (user != null) {
            if (!ValidateCodeServlet.validate(request, validateCode)) {
                request.setAttribute("isRegister", "验证码错误！");
                return "redirect:" + frontPath + "/enter";
            }

//          User user = UserUtils.getByLoginName(username);
            HkUserShop hkUserShop = hkUserShopService.getShopByUserId(user.getId());
            if (null != hkUserShop) {
                UserUtils.setShopId(hkUserShop.getId());
            }


            if (SystemService.validatePassword(password, user.getPassword())) {
                UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray(), false, StringUtils.getRemoteAddr((HttpServletRequest) request), validateCode, false);
                Subject currentUser = SecurityUtils.getSubject();
                try {
                    if (!currentUser.isAuthenticated()) {
                        currentUser.login(token);//验证角色和权限
                    }
                } catch (Exception e) {

                }
                request.getSession().setAttribute("loginName", UserUtils.getUser().getLoginName());
                Principal principal = UserUtils.getPrincipal();
                HkShopReview hkShopReview = hkShopReviewService.getReShopReviewByLoginName(username);
                if (hkShopReview == null) {
                    //还未提交资料
                    HkUserShopEnter hkUserShopEnter = new HkUserShopEnter();
                    model.addAttribute("hkUserShopEnter", hkUserShopEnter);
                    return "modules/cms/shop/userShopEnter";
                } else {
                    // 0-审核中 1-审核通过  2-审核未通过
                    if (hkShopReview.getCreateDate() != null) {
                        request.setAttribute("createDate", DateUtils.formatDate(hkShopReview.getCreateDate(), "yyyy-MM-dd"));
                    } else {
                        request.setAttribute("createDate", "");
                    }
                    if (hkShopReview.getReviewBeginDate() != null) {
                        request.setAttribute("beginDate", DateUtils.formatDate(hkShopReview.getReviewBeginDate(), "yyyy-MM-dd"));
                    } else {
                        request.setAttribute("beginDate", "");
                    }
                    if (hkShopReview.getReviewEndDate() != null) {
                        request.setAttribute("endDate", DateUtils.formatDate(hkShopReview.getReviewEndDate(), "yyyy-MM-dd"));
                    } else {
                        request.setAttribute("endDate", "");
                    }

                    if (hkShopReview.getReviewStatus().equals("0")) {
                        return "modules/cms/shop/checkInExamine";
                    } else if (hkShopReview.getReviewStatus().equals("2")) {
                        request.setAttribute("state", hkShopReview.getReviewStatus());
                        request.setAttribute("failMsg", hkShopReview.getReviewFailMsg());
                        addMessage(redirectAttributes, "审核未通过，请重新填写入驻资料！");
                        return "modules/cms/shop/checkInPass";
                    } else {
                        if (principal != null) return "redirect:" + adminPath;
                        return "redirect:" + frontPath + "/enter";
                    }
                }
            } else {
                request.setAttribute("isRegister", "密码错误！");
//                return "redirect:" + frontPath + "/enter";
                return "modules/cms/shop/enter";
            }
        } else {
            request.setAttribute("isRegister", "请先申请商家入驻！");
//            return "redirect:" + frontPath + "/enter";
            return "modules/cms/shop/enter";
        }
    }


    /**
     * 忘记密码
     */
    @RequestMapping(value = "userForgetPassword")
    public String userForgetPassword(Model model) {
        System.out.println("找回密码");
        Site site = CmsUtils.getSite(Site.defaultSiteId());
        model.addAttribute("site", site);
        return "modules/cms/shop/pwd/forgetPassword";
    }

    /**
     * 修改密码页面
     */
    @RequestMapping(value = "goUserForgetPassword")
    public String goUserForgetPassword(String code, String loginName, HttpServletRequest request) {

        String oldCode = request.getSession().getAttribute("code").toString();
        if (code != null && loginName != null) {
            if (systemService.getUserByLoginName(loginName) != null && oldCode.equals(code)) {
                request.setAttribute("tel", loginName);
                return "modules/cms/shop/pwd/resetPassword";
            } else {
                return "modules/cms/shop/pwd/forgetPassword";
            }
        } else {
            return "modules/cms/shop/pwd/forgetPassword";
        }
    }


    /**
     * 修改密码操作
     */
    @RequestMapping(value = "updateUserForgetPassword")
    public String updateUserForgetPassword(String username, String password, HttpServletRequest request) {
        String a = "modules/cms/shop/pwd/modifyPassword";
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            hkUserService.updatePasswordByName(username, password);
        } else {
            a = "modules/cms/shop/pwd/resetPassword";
        }
        return a;
    }

    /**
     * 提交商铺入驻信息
     *
     * @param hkUserShopEnter
     * @param model
     * @return
     */
    @RequestMapping(value = "userShopEnter")
    public String userShopEnter(HkUserShopEnter hkUserShopEnter, Model model, HttpServletRequest request) {

        if (StringUtils.isBlank(UserUtils.getShopId())) {
            model.addAttribute("hkUserShopEnter", hkUserShopEnter);
            addMessage(model, "登录超时，请重新登录！");
            return "redirect:" + Global.getFrontPath();
        }


        if (!beanValidator(model, hkUserShopEnter)) {
            model.addAttribute("hkUserShopEnter", hkUserShopEnter);
            addMessage(model, "信息填写错误，请您认真查看填写信息！");
            return "modules/cms/shop/userShopEnter";
        }

        try {
            request.setAttribute("state", "1");
            request.setAttribute("createDate", DateUtils.getDate());
            request.setAttribute("beginDate", DateUtils.getDate());
            request.setAttribute("endDate", DateUtils.getDate());
            hkShopReviewService.svaeUserShopEnter(hkUserShopEnter);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("hkUserShopEnter", hkUserShopEnter);
            addMessage(model, "入驻信息提交失败，请您稍后重试！");
            return "modules/cms/shop/userShopEnter";
        }
        return "modules/cms/shop/checkInPass";
    }

    /**
     * 重新申请
     *
     * @return
     */
    @RequestMapping(value = "registerAgain")
    public String registerAgain(Model model) {
        HkUserShopEnter hkUserShopEnter = hkShopReviewService.registerAgain();
        model.addAttribute("hkUserShopEnter", hkUserShopEnter);
        return "modules/cms/shop/userShopEnter";
    }


    /**
     * 网站首页
     */
    @RequestMapping(value = "index-{siteId}${urlSuffix}")
    public String index(@PathVariable String siteId, Model model) {
        if (siteId.equals("1")) {
            return "redirect:" + Global.getFrontPath();
        }
        Site site = CmsUtils.getSite(siteId);
        // 子站有独立页面，则显示独立页面
        if (StringUtils.isNotBlank(site.getCustomIndexView())) {
            model.addAttribute("site", site);
            model.addAttribute("isIndex", true);
            return "modules/cms/front/themes/" + site.getTheme() + "/frontIndex" + site.getCustomIndexView();
        }
        // 否则显示子站第一个栏目
        List<Category> mainNavList = CmsUtils.getMainNavList(siteId);
        if (mainNavList.size() > 0) {
            String firstCategoryId = CmsUtils.getMainNavList(siteId).get(0).getId();
            return "redirect:" + Global.getFrontPath() + "/list-" + firstCategoryId + Global.getUrlSuffix();
        } else {
            model.addAttribute("site", site);
            return "modules/cms/front/themes/" + site.getTheme() + "/frontListCategory";
        }
    }

    /**
     * 内容列表
     */
    @RequestMapping(value = "list-{categoryId}${urlSuffix}")
    public String list(@PathVariable String categoryId, @RequestParam(required = false, defaultValue = "1") Integer
            pageNo,
                       @RequestParam(required = false, defaultValue = "15") Integer pageSize, Model model) {
        Category category = categoryService.get(categoryId);
        if (category == null) {
            Site site = CmsUtils.getSite(Site.defaultSiteId());
            model.addAttribute("site", site);
            return "error/404";
        }
        Site site = siteService.get(category.getSite().getId());
        model.addAttribute("site", site);
        // 2：简介类栏目，栏目第一条内容
        if ("2".equals(category.getShowModes()) && "article".equals(category.getModule())) {
            // 如果没有子栏目，并父节点为跟节点的，栏目列表为当前栏目。
            List<Category> categoryList = Lists.newArrayList();
            if (category.getParent().getId().equals("1")) {
                categoryList.add(category);
            } else {
                categoryList = categoryService.findByParentId(category.getParent().getId(), category.getSite().getId());
            }
            model.addAttribute("category", category);
            model.addAttribute("categoryList", categoryList);
            // 获取文章内容
            Page<Article> page = new Page<Article>(1, 1, -1);
            Article article = new Article(category);
            page = articleService.findPage(page, article, false);
            if (page.getList().size() > 0) {
                article = page.getList().get(0);
                article.setArticleData(articleDataService.get(article.getId()));
                articleService.updateHitsAddOne(article.getId());
            }
            model.addAttribute("article", article);
            CmsUtils.addViewConfigAttribute(model, category);
            CmsUtils.addViewConfigAttribute(model, article.getViewConfig());
            return "modules/cms/front/themes/" + site.getTheme() + "/" + getTpl(article);
        } else {
            List<Category> categoryList = categoryService.findByParentId(category.getId(), category.getSite().getId());
            // 展现方式为1 、无子栏目或公共模型，显示栏目内容列表
            if ("1".equals(category.getShowModes()) || categoryList.size() == 0) {
                // 有子栏目并展现方式为1，则获取第一个子栏目；无子栏目，则获取同级分类列表。
                if (categoryList.size() > 0) {
                    category = categoryList.get(0);
                } else {
                    // 如果没有子栏目，并父节点为跟节点的，栏目列表为当前栏目。
                    if (category.getParent().getId().equals("1")) {
                        categoryList.add(category);
                    } else {
                        categoryList = categoryService.findByParentId(category.getParent().getId(), category.getSite().getId());
                    }
                }
                model.addAttribute("category", category);
                model.addAttribute("categoryList", categoryList);
                // 获取内容列表
                if ("article".equals(category.getModule())) {
                    Page<Article> page = new Page<Article>(pageNo, pageSize);
                    //System.out.println(page.getPageNo());
                    page = articleService.findPage(page, new Article(category), false);
                    model.addAttribute("page", page);
                    // 如果第一个子栏目为简介类栏目，则获取该栏目第一篇文章
                    if ("2".equals(category.getShowModes())) {
                        Article article = new Article(category);
                        if (page.getList().size() > 0) {
                            article = page.getList().get(0);
                            article.setArticleData(articleDataService.get(article.getId()));
                            articleService.updateHitsAddOne(article.getId());
                        }
                        model.addAttribute("article", article);
                        CmsUtils.addViewConfigAttribute(model, category);
                        CmsUtils.addViewConfigAttribute(model, article.getViewConfig());
                        return "modules/cms/front/themes/" + site.getTheme() + "/" + getTpl(article);
                    }
                } else if ("link".equals(category.getModule())) {
                    Page<Link> page = new Page<Link>(1, -1);
                    page = linkService.findPage(page, new Link(category), false);
                    model.addAttribute("page", page);
                }
                String view = "/frontList";
                if (StringUtils.isNotBlank(category.getCustomListView())) {
                    view = "/" + category.getCustomListView();
                }
                CmsUtils.addViewConfigAttribute(model, category);
                site = siteService.get(category.getSite().getId());
                //System.out.println("else 栏目第一条内容 _2 :"+category.getSite().getTheme()+","+site.getTheme());
                return "modules/cms/front/themes/" + siteService.get(category.getSite().getId()).getTheme() + view;
                //return "modules/cms/front/themes/"+category.getSite().getTheme()+view;
            }
            // 有子栏目：显示子栏目列表
            else {
                model.addAttribute("category", category);
                model.addAttribute("categoryList", categoryList);
                String view = "/frontListCategory";
                if (StringUtils.isNotBlank(category.getCustomListView())) {
                    view = "/" + category.getCustomListView();
                }
                CmsUtils.addViewConfigAttribute(model, category);
                return "modules/cms/front/themes/" + site.getTheme() + view;
            }
        }
    }

    /**
     * 内容列表（通过url自定义视图）
     */
    @RequestMapping(value = "listc-{categoryId}-{customView}${urlSuffix}")
    public String listCustom(@PathVariable String categoryId, @PathVariable String
            customView, @RequestParam(required = false, defaultValue = "1") Integer pageNo,
                             @RequestParam(required = false, defaultValue = "15") Integer pageSize, Model model) {
        Category category = categoryService.get(categoryId);
        if (category == null) {
            Site site = CmsUtils.getSite(Site.defaultSiteId());
            model.addAttribute("site", site);
            return "error/404";
        }
        Site site = siteService.get(category.getSite().getId());
        model.addAttribute("site", site);
        List<Category> categoryList = categoryService.findByParentId(category.getId(), category.getSite().getId());
        model.addAttribute("category", category);
        model.addAttribute("categoryList", categoryList);
        CmsUtils.addViewConfigAttribute(model, category);
        return "modules/cms/front/themes/" + site.getTheme() + "/frontListCategory" + customView;
    }

    /**
     * 显示内容
     */
    @RequestMapping(value = "view-{categoryId}-{contentId}${urlSuffix}")
    public String view(@PathVariable String categoryId, @PathVariable String contentId, Model model) {
        Category category = categoryService.get(categoryId);
        if (category == null) {
            Site site = CmsUtils.getSite(Site.defaultSiteId());
            model.addAttribute("site", site);
            return "error/404";
        }
        model.addAttribute("site", category.getSite());
        if ("article".equals(category.getModule())) {
            // 如果没有子栏目，并父节点为跟节点的，栏目列表为当前栏目。
            List<Category> categoryList = Lists.newArrayList();
            if (category.getParent().getId().equals("1")) {
                categoryList.add(category);
            } else {
                categoryList = categoryService.findByParentId(category.getParent().getId(), category.getSite().getId());
            }
            // 获取文章内容
            Article article = articleService.get(contentId);
            if (article == null || !Article.DEL_FLAG_NORMAL.equals(article.getDelFlag())) {
                return "error/404";
            }
            // 文章阅读次数+1
            articleService.updateHitsAddOne(contentId);
            // 获取推荐文章列表
            List<Object[]> relationList = articleService.findByIds(articleDataService.get(article.getId()).getRelation());
            // 将数据传递到视图
            model.addAttribute("category", categoryService.get(article.getCategory().getId()));
            model.addAttribute("categoryList", categoryList);
            article.setArticleData(articleDataService.get(article.getId()));
            model.addAttribute("article", article);
            model.addAttribute("relationList", relationList);
            CmsUtils.addViewConfigAttribute(model, article.getCategory());
            CmsUtils.addViewConfigAttribute(model, article.getViewConfig());
            Site site = siteService.get(category.getSite().getId());
            model.addAttribute("site", site);
//			return "modules/cms/front/themes/"+category.getSite().getTheme()+"/"+getTpl(article);
            return "modules/cms/front/themes/" + site.getTheme() + "/" + getTpl(article);
        }
        return "error/404";
    }

    /**
     * 内容评论
     */
    @RequestMapping(value = "comment", method = RequestMethod.GET)
    public String comment(String theme, Comment comment, HttpServletRequest request, HttpServletResponse
            response, Model model) {
        Page<Comment> page = new Page<Comment>(request, response);
        Comment c = new Comment();
        c.setCategory(comment.getCategory());
        c.setContentId(comment.getContentId());
        c.setDelFlag(Comment.DEL_FLAG_NORMAL);
        page = commentService.findPage(page, c);
        model.addAttribute("page", page);
        model.addAttribute("comment", comment);
        return "modules/cms/front/themes/" + theme + "/frontComment";
    }

    /**
     * 内容评论保存
     */
    @ResponseBody
    @RequestMapping(value = "comment", method = RequestMethod.POST)
    public String commentSave(Comment comment, String validateCode, @RequestParam(required = false) String
            replyId, HttpServletRequest request) {
        if (StringUtils.isNotBlank(validateCode)) {
            if (ValidateCodeServlet.validate(request, validateCode)) {
                if (StringUtils.isNotBlank(replyId)) {
                    Comment replyComment = commentService.get(replyId);
                    if (replyComment != null) {
                        comment.setContent("<div class=\"reply\">" + replyComment.getName() + ":<br/>"
                                + replyComment.getContent() + "</div>" + comment.getContent());
                    }
                }
                comment.setIp(request.getRemoteAddr());
                comment.setCreateDate(new Date());
                comment.setDelFlag(Comment.DEL_FLAG_AUDIT);
                commentService.save(comment);
                return "{result:1, message:'提交成功。'}";
            } else {
                return "{result:2, message:'验证码不正确。'}";
            }
        } else {
            return "{result:2, message:'验证码不能为空。'}";
        }
    }

    /**
     * 站点地图
     */
    @RequestMapping(value = "map-{siteId}${urlSuffix}")
    public String map(@PathVariable String siteId, Model model) {
        Site site = CmsUtils.getSite(siteId != null ? siteId : Site.defaultSiteId());
        model.addAttribute("site", site);
        return "modules/cms/front/themes/" + site.getTheme() + "/frontMap";
    }

    private String getTpl(Article article) {
        if (StringUtils.isBlank(article.getCustomContentView())) {
            String view = null;
            Category c = article.getCategory();
            boolean goon = true;
            do {
                if (StringUtils.isNotBlank(c.getCustomContentView())) {
                    view = c.getCustomContentView();
                    goon = false;
                } else if (c.getParent() == null || c.getParent().isRoot()) {
                    goon = false;
                } else {
                    c = c.getParent();
                }
            } while (goon);
            return StringUtils.isBlank(view) ? Article.DEFAULT_TEMPLATE : view;
        } else {
            return article.getCustomContentView();
        }
    }


    /**
     * 商家入驻-身份认证
     */
    @RequestMapping(value = "saveHkEnterShopInfo")
    public String saveHkEnterShopInfoService(HkEnterShopInfo hkEnterShopInfo, Model model, HttpSession session) {
        try {

            log.info("saveHkEnterShopInfo-shopId", UserUtils.getShopId());
            log.info("saveHkEnterShopInfo-loginName", UserUtils.getSession().getAttribute("loginName"));

            if (!beanValidator(model, hkEnterShopInfo)) {
                return formEnterShopInfo(hkEnterShopInfo, model);
            }

            hkEnterShopInfo.setShop(hkUserShopService.get(UserUtils.getShopId()));
            hkEnterShopInfoService.save(hkEnterShopInfo);
            HkEnterShopCompanyInfo hkEnterShopCompanyInfo = new HkEnterShopCompanyInfo();
            model.addAttribute("hkEnterShopCompanyInfo", hkEnterShopCompanyInfo);
            return "modules/cms/shop/enterShopCompanyInfoForm";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("hkEnterShopInfo", hkEnterShopInfo);
            return "modules/cms/shop/enterShopInfoForm";
        }
    }


    @RequestMapping(value = "formEnterShopInfo")
    public String formEnterShopInfo(HkEnterShopInfo hkEnterShopInfo, Model model) {
        model.addAttribute("hkEnterShopInfo", hkEnterShopInfo);
        return "modules/cms/shop/enterShopInfoForm";
    }


    /**
     * 商家入驻-企业认证
     */
    @RequestMapping(value = "saveHkEnterShopCompanyInfoForm")
    public String saveHkEnterShopCompanyInfoForm(HkEnterShopCompanyInfo hkEnterShopCompanyInfo, Model
            model, HttpSession session) {
        try {

            String areaId = hkEnterShopCompanyInfo.getArea().getId();
            //根据叶子节点获取父节点

            String parentIds = areaService.getCode(areaId);
            String[] str = parentIds.split(",");
            hkEnterShopCompanyInfo.setProvinceCode(str[0]);
            hkEnterShopCompanyInfo.setCityCode(str[1]);
            hkEnterShopCompanyInfo.setAreaCode(areaId);
            hkEnterShopCompanyInfo.setShop(hkUserShopService.get(UserUtils.getShopId()));
            hkEnterShopCompanyInfoService.save(hkEnterShopCompanyInfo);
            HkShopTrademark hkShopTrademark = new HkShopTrademark();
            model.addAttribute("hkShopTrademark", hkShopTrademark);
            return "modules/cms/shop/shopTrademarkForm";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(hkEnterShopCompanyInfo);
            return "modules/cms/shop/enterShopCompanyInfoForm";
        }
    }


    @RequestMapping(value = "jumpCompanyForm")
    public String jumpCompanyForm(Model model) {
        HkShopTrademark hkShopTrademark = new HkShopTrademark();
        model.addAttribute("hkShopTrademark", hkShopTrademark);
        return "modules/cms/shop/shopTrademarkForm";
    }


    /**
     * 商家入驻-商标信息
     */
    @RequestMapping(value = "saveHkShopTrademarkForm")
    public String saveHkShopTrademarkForm(Model model, HkShopTrademark hkShopTrademark, HttpSession session) {
        try {

            if (!beanValidator(model, hkShopTrademark)) {
                return formHkShopTrademark(hkShopTrademark, model);
            }
            hkShopTrademark.setShop(hkUserShopService.get(UserUtils.getShopId()));
            hkShopTrademarkService.save(hkShopTrademark);
            HkUserShop hkUserShop = new HkUserShop();
            model.addAttribute("hkUserShop", hkUserShop);
            return "modules/cms/shop/userShopForm";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute(hkShopTrademark);
            return "modules/cms/shop/shopTrademarkForm";
        }
    }


    @RequestMapping(value = "formHkShopTrademark")
    public String formHkShopTrademark(HkShopTrademark hkShopTrademark, Model model) {
        model.addAttribute("hkShopTrademark", hkShopTrademark);
        return "modules/cms/shop/shopTrademarkForm";
    }


    @RequestMapping(value = "jumptrademarkForm")
    public String jumptrademarkForm(Model model) {
        HkUserShop hkUserShop = new HkUserShop();
        model.addAttribute("hkUserShop", hkUserShop);
        return "modules/cms/shop/userShopForm";
    }


    /**
     * 商家入驻-店铺商品信息
     */

    @RequestMapping(value = "saveHkUserShopForm")
    public String saveHkUserShopForm(HttpServletRequest request, HkUserShop hkUserShop, RedirectAttributes redirectAttributes, Model model) {
        try {

            log.info("saveHkUserShopForm-shopId", UserUtils.getShopId());
            log.info("saveHkUserShopForm-loginName", UserUtils.getSession().getAttribute("loginName"));

            if (!beanValidator(model, hkUserShop)) {
                model.addAttribute("hkUserShop", hkUserShop);
                return formHkUserShop(hkUserShop, model);
            }

            hkShopReviewService.saveReview(hkUserShop);
            request.setAttribute("createDate", DateUtils.getDate());
            request.setAttribute("beginDate", "");
            model.addAttribute("hkUserShop", hkUserShop);
            return "modules/cms/shop/checkInExamine";

        } catch (Exception e) {
            model.addAttribute("hkUserShop", hkUserShop);
            addMessage(redirectAttributes, "入驻信息提交失败，请稍后重试！");
            return "modules/cms/shop/userShopForm";
        }
    }


    @RequestMapping(value = "formHkUserShop")
    public String formHkUserShop(HkUserShop hkUserShop, Model model) {
        model.addAttribute("hkUserShop", hkUserShop);
        return "modules/cms/shop/userShopForm";
    }

    /**
     * 查看店铺审核状态(暂时不用该方法查看)
     */
    @RequestMapping(value = "getShopReview")
    @ResponseBody
    public HkShopReview getShopReview(RedirectAttributes redirectAttributes, HttpServletRequest request) {
        HkShopReview hkShopReview = null;
        String shopId = request.getParameter("shopId");
        try {
            hkShopReview = hkShopReviewService.getShopReviewByShopId(shopId);
        } catch (Exception e) {
            e.printStackTrace();
            addMessage(redirectAttributes, "查看审核状态异常，请稍后重试！");
        }
        return hkShopReview;
    }


    /**
     * 招商合作
     *
     * @return
     */
    @RequestMapping(value = "saveCooperation")
    public String saveCooperation(String username, String mobile, String coop, String area) {
        HkShopCooperation hkShopCooperation = new HkShopCooperation();
        hkShopCooperation.setUsername(username);
        hkShopCooperation.setMobile(mobile);
        hkShopCooperation.setOccupation(coop);
        hkShopCooperation.setAreaName(area);
        hkShopCooperationService.save(hkShopCooperation);
        return "modules/cms/shop/enter";
    }


}

